package Util;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Properties;

/**
 * Contains a few useful methods
 *
 */
public class Util {
	
	/**
	 * Get a value from a properties file
	 * @param file properties file path
	 * @param attr attribute name to extract
	 * @return the value of this attribute
	 */
	public static String getPropertiesAttribute(String file, String attr){
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(file));
			String res = prop.getProperty(attr);
			return res;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * Get a list of values from a properties file
	 * @param file file properties file path
	 * @param attr attribute name to extract. This attribute owns a list of values
	 * @return the values of this attribute
	 */
	public static String[] getPropertiesList(String file, String attr){
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(file));
			String res = prop.getProperty(attr);
			return parseList(res);

		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * Parse a string
	 * @param res string respecting the pattern "{str0, str1, ..., strn}"
	 * @return a list of strings containing (str0,str1,...,strn)
	 */
	private static String[] parseList(String res){
		res = res.replaceAll(" ", "");
		res = res.replace("{", "");
		res = res.replace("}", "");
		ArrayList<String> list = new ArrayList<String>();
		String temp = "";
		for(int i = 0; i < res.length(); i++){
			if(res.charAt(i)==','){
				list.add(temp);
				temp = "";
			}else{
				temp = temp + res.charAt(i);
			}
			
		}
		list.add(temp);
		String[] tab = new String[list.size()];
		for(int i = 0; i < list.size(); i++)
			tab[i] = list.get(i);
		
		
		return tab;
	}

	

}
